// 应用主逻辑
new Vue({
    el: '#app',
    data: {
        // 页面状态
        currentPage: 'login', // login, register, forgotPassword, main, accountDetail, addAccount, editAccount, settings
        isLoading: false,
        errorMessage: '',
        successMessage: '',
        
        // 登录表单
        loginForm: {
            username: '',
            password: '',
            showPassword: false,
            rememberMe: false
        },
        
        // 注册表单
        registerForm: {
            username: '',
            password: '',
            confirmPassword: '',
            showPassword: false
        },
        
        // 忘记密码表单
        forgotForm: {
            username: ''
        },
        
        // 账号表单 (新增/编辑)
        accountForm: {
            id: null,
            name: '',
            url: '',
            username: '',
            password: '',
            showPassword: false,
            categoryId: '1',
            note: ''
        },
        
        // 当前查看的账号
        currentAccount: {},
        
        // 账号列表数据
        accounts: [],
        categories: [
            { id: '1', name: '全部' },
            { id: '2', name: '网站' },
            { id: '3', name: '应用' },
            { id: '4', name: '社交媒体' },
            { id: '5', name: '金融' },
            { id: '6', name: '其他' }
        ],
        
        // 搜索和筛选
        searchQuery: '',
        selectedCategory: '1',
        
        // 设置相关
        autoLockTime: '300000',
        requirePasswordOnStart: true,
        
        // 对话框状态
        showChangePasswordDialog: false,
        showGeneratePasswordDialog: false, // 确保默认为false，不会自动弹出
        showRestoreDialog: false,
        showAboutDialog: false,
        
        // 修改密码表单
        changePasswordForm: {
            currentPassword: '',
            newPassword: '',
            confirmPassword: ''
        },
        
        // 密码生成器
        passwordGenerator: {
            length: 12,
            includeUppercase: true,
            includeLowercase: true,
            includeNumbers: true,
            includeSymbols: true
        },
        generatedPassword: '',
        
        // 加密密钥
        encryptionKey: null,
        
        // URL验证错误
        urlError: ''
    },
    
    computed: {
        // 过滤后的账号列表
        filteredAccounts() {
            let result = [...this.accounts];
            
            // 按分类筛选
            if (this.selectedCategory !== '1') {
                result = result.filter(account => account.categoryId === this.selectedCategory);
            }
            
            // 按搜索词筛选 - 只搜索网站名称，支持模糊搜索
            if (this.searchQuery) {
                const query = this.searchQuery.toLowerCase();
                result = result.filter(account => 
                    account.name.toLowerCase().includes(query)
                );
            }
            
            return result;
        },
        
        // 密码强度评估
        passwordStrengthClass() {
            const password = this.registerForm.password;
            if (!password) return '';
            
            const strength = this.evaluatePasswordStrength(password);
            if (strength < 3) return 'weak';
            if (strength < 6) return 'medium';
            return 'strong';
        },
        
        passwordStrengthText() {
            const password = this.registerForm.password;
            if (!password) return '';
            
            const strength = this.evaluatePasswordStrength(password);
            if (strength < 3) return '弱密码，请增加复杂度';
            if (strength < 6) return '中等强度';
            return '强密码，很安全';
        }
    },
    
    mounted() {
        // 检查本地存储中的登录状态
        const savedUser = localStorage.getItem('user');
        const savedKey = localStorage.getItem('encryptionKey');
        const token = localStorage.getItem('token');
        
        if (savedUser && savedKey && token && token.trim()) {
            this.encryptionKey = savedKey;
            // 正确设置axios默认headers
            const authHeader = `Bearer ${token}`;
            axios.defaults.headers.common['Authorization'] = authHeader;
            console.log('初始化时设置Authorization头:', authHeader);
            this.loadAccounts();
            this.switchTo('main');
        } else {
            // 清除可能存在的无效Authorization头
            delete axios.defaults.headers.common['Authorization'];
            console.log('清除无效的Authorization头');
        }
        
        // 确保密码生成对话框不会自动弹出
        this.showGeneratePasswordDialog = false;
        console.log('应用初始化完成，密码生成对话框状态:', this.showGeneratePasswordDialog);
    },
    
    methods: {
        // 页面切换
        switchTo(page) {
            this.currentPage = page;
            this.errorMessage = '';
            this.successMessage = '';
            
            // 重置表单
            if (page === 'addAccount') {
                this.resetAccountForm();
            }
        },
        
        // 密码显示/隐藏切换
        toggleLoginPasswordVisibility() {
            this.loginForm.showPassword = !this.loginForm.showPassword;
        },
        
        toggleRegisterPasswordVisibility() {
            this.registerForm.showPassword = !this.registerForm.showPassword;
        },
        
        toggleAccountPasswordVisibility() {
            this.accountForm.showPassword = !this.accountForm.showPassword;
        },
        
        toggleDetailPasswordVisibility() {
            this.currentAccount.showPassword = !this.currentAccount.showPassword;
        },
        
        // 加密函数
        encrypt(text) {
            if (!this.encryptionKey) return text;
            return CryptoJS.AES.encrypt(text, this.encryptionKey).toString();
        },
        
        // 解密函数
        decrypt(text) {
            if (!this.encryptionKey || !text) return text;
            try {
                const bytes = CryptoJS.AES.decrypt(text, this.encryptionKey);
                return bytes.toString(CryptoJS.enc.Utf8);
            } catch (e) {
                console.error('解密失败:', e);
                return text;
            }
        },
        
        // 生成加密密钥
        generateEncryptionKey(password) {
            return CryptoJS.SHA256(password).toString();
        },
        
        // 登录
        async login() {
            try {
                this.isLoading = true;
                this.errorMessage = '';
                
                // 生成加密密钥
                this.encryptionKey = this.generateEncryptionKey(this.loginForm.password);
                
                // 调用后端API登录
                const response = await axios.post('/api/users/login', {
                    username: this.loginForm.username,
                    password: this.loginForm.password
                });
                
                // 保存用户信息和token
                if (this.loginForm.rememberMe) {
                    localStorage.setItem('user', this.loginForm.username);
                    localStorage.setItem('encryptionKey', this.encryptionKey);
                }
                // 确保token存在且有效
                // 从正确的路径获取token：response.data.data.token
                const token = response.data?.data?.token;
                if (token) {
                    localStorage.setItem('token', token);
                    // 正确设置axios默认headers
                    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
                    console.log('已设置Authorization头:', axios.defaults.headers.common['Authorization']);
                } else {
                    console.error('登录成功但未收到有效的token，响应结构:', JSON.stringify(response.data || {}));
                }
                
                this.loadAccounts();
                this.switchTo('main');
                this.isLoading = false;
                
            } catch (error) {
                this.errorMessage = error.response?.data?.message || '登录失败，请检查用户名和密码';
                this.isLoading = false;
            }
        },
        
        // 注册
        async register() {
            try {
                this.isLoading = true;
                this.errorMessage = '';
                
                // 验证密码是否匹配
                if (this.registerForm.password !== this.registerForm.confirmPassword) {
                    this.errorMessage = '两次输入的密码不一致';
                    this.isLoading = false;
                    return;
                }
                
                // 验证密码强度
                if (this.evaluatePasswordStrength(this.registerForm.password) < 3) {
                    this.errorMessage = '密码强度不足，请使用更复杂的密码';
                    this.isLoading = false;
                    return;
                }
                
                // 调用后端API注册
                const response = await axios.post('/api/users/register', {
                    username: this.registerForm.username,
                    password: this.registerForm.password
                });
                
                this.successMessage = '注册成功，请登录';
                setTimeout(() => {
                    this.switchTo('login');
                    this.loginForm.username = this.registerForm.username;
                }, 1500);
                this.isLoading = false;
                
            } catch (error) {
                this.errorMessage = error.response?.data?.message || '注册失败，请稍后重试';
                this.isLoading = false;
            }
        },
        
        // 忘记密码
        async forgotPassword() {
            try {
                this.isLoading = true;
                this.errorMessage = '';
                
                // 调用后端API重置密码
                const response = await axios.post('/api/users/forgot-password', {
                    username: this.forgotForm.username
                });
                
                this.successMessage = '重置密码链接已发送到您的邮箱';
                this.isLoading = false;
                
            } catch (error) {
                this.errorMessage = error.response?.data?.message || '处理失败，请稍后重试';
                this.isLoading = false;
            }
        },
        
        // 退出登录
        logout() {
            localStorage.removeItem('user');
            localStorage.removeItem('encryptionKey');
            localStorage.removeItem('token');
            delete axios.defaults.headers.common['Authorization'];
            this.encryptionKey = null;
            this.accounts = [];
            this.switchTo('login');
        },
        
        // 加载账号列表
        async loadAccounts() {
            try {
                this.isLoading = true;
                
                // 调用后端API获取账号列表
                const response = await axios.get('/api/accounts');
                
                // 解密密码
                // 从正确的路径获取账号列表数组：response.data.data
                const accountsData = response.data?.data || [];
                if (!Array.isArray(accountsData)) {
                    console.error('账号列表数据格式错误:', accountsData);
                    this.accounts = [];
                } else {
                    this.accounts = accountsData.map(account => ({
                        ...account,
                        password: this.decrypt(account.password),
                        showPassword: false
                    }));
                }
                
                // 加载分类列表
                this.loadCategories();
                
                this.isLoading = false;
            } catch (error) {
                console.error('加载账号失败:', error);
                this.accounts = [];
                this.isLoading = false;
                this.errorMessage = '加载账号失败，请重试';
            }
        },
        
        // 加载分类列表
        async loadCategories() {
            try {
                const response = await axios.get('/api/categories');
                // 从正确的路径获取分类列表数组：response.data.data
                const categoriesData = response.data?.data || [];
                if (!Array.isArray(categoriesData)) {
                    console.error('分类列表数据格式错误:', categoriesData);
                    this.categories = [{ id: '1', name: '全部' }];
                } else {
                    this.categories = [
                        { id: '1', name: '全部' },
                        ...categoriesData.map(cat => ({ id: cat.id.toString(), name: cat.name }))
                    ];
                }
            } catch (error) {
                console.error('加载分类失败:', error);
                this.categories = [{ id: '1', name: '全部' }];
            }
        },
        
        // 查看账号详情
        viewAccountDetail(id) {
            const account = this.accounts.find(acc => acc.id === id);
            if (account) {
                this.currentAccount = { ...account, showPassword: false };
                this.switchTo('accountDetail');
            }
        },
        
        // 重置账号表单
        resetAccountForm() {
            this.accountForm = {
                id: null,
                name: '',
                url: '',
                username: '',
                password: '',
                showPassword: false,
                categoryId: '2',
                note: ''
            };
            this.urlError = '';
        },
        
        // 编辑账号
        editAccount(id) {
            const account = this.accounts.find(acc => acc.id === id);
            if (account) {
                this.accountForm = { ...account, showPassword: false };
                this.switchTo('editAccount');
            }
        },
        
        // 删除账号
        async deleteAccount(id) {
            if (confirm('确定要删除这个账号吗？')) {
                try {
                    this.isLoading = true;
                    
                    // 调用后端API删除账号
                    await axios.delete(`/api/accounts/${id}`);
                    
                    // 重新加载账号列表
                    this.loadAccounts();
                    
                    if (this.currentPage === 'accountDetail') {
                        this.switchTo('main');
                    }
                    
                    this.successMessage = '账号已删除';
                    setTimeout(() => {
                        this.successMessage = '';
                    }, 3000);
                    
                    this.isLoading = false;
                } catch (error) {
                    this.errorMessage = error.response?.data?.message || '删除失败，请稍后重试';
                    this.isLoading = false;
                }
            }
        },
        
        // 保存账号
        async saveAccount() {
            try {
                this.isLoading = true;
                this.errorMessage = '';
                
                if (this.urlError) {
                    return;
                }
                
                const accountData = {
                    name: this.accountForm.name,
                    url: this.accountForm.url,
                    username: this.accountForm.username,
                    password: this.encrypt(this.accountForm.password), // 加密后发送
                    categoryId: this.accountForm.categoryId !== '0' ? this.accountForm.categoryId : null,
                    note: this.accountForm.note
                };
                
                let response;
                if (this.accountForm.id) {
                    // 编辑现有账号
                    response = await axios.put(`/api/accounts/${this.accountForm.id}`, accountData);
                } else {
                    // 新增账号
                    response = await axios.post('/api/accounts', accountData);
                }
                
                // 重新加载账号列表
                this.loadAccounts();
                this.switchTo('main');
                
                this.successMessage = this.accountForm.id ? '账号已更新' : '账号已添加';
                setTimeout(() => {
                    this.successMessage = '';
                }, 3000);
                
                this.isLoading = false;
                
            } catch (error) {
                this.errorMessage = error.response?.data?.message || '保存失败，请稍后重试';
                this.isLoading = false;
            }
        },
        
        // 搜索账号
        searchAccounts() {
            // 搜索逻辑已在computed中实现，这里确保Vue能响应searchQuery的变化
            this.$forceUpdate(); // 强制更新视图
            console.log('搜索网站名称:', this.searchQuery);
        },
        
        // 选择分类
        selectCategory(categoryId) {
            this.selectedCategory = categoryId;
        },
        
        // 修改密码
        async changePassword() {
            try {
                this.isLoading = true;
                this.errorMessage = '';
                
                // 验证新密码
                if (this.changePasswordForm.newPassword !== this.changePasswordForm.confirmPassword) {
                    this.errorMessage = '两次输入的新密码不一致';
                    this.isLoading = false;
                    return;
                }
                
                // 调用后端API修改密码
                await axios.put('/api/users/change-password', {
                    currentPassword: this.changePasswordForm.currentPassword,
                    newPassword: this.changePasswordForm.newPassword
                });
                
                // 更新本地加密密钥
                this.encryptionKey = this.generateEncryptionKey(this.changePasswordForm.newPassword);
                localStorage.setItem('encryptionKey', this.encryptionKey);
                
                this.showChangePasswordDialog = false;
                this.changePasswordForm = {
                    currentPassword: '',
                    newPassword: '',
                    confirmPassword: ''
                };
                
                this.successMessage = '密码已修改';
                this.isLoading = false;
                
            } catch (error) {
                this.errorMessage = error.response?.data?.message || '修改失败，请稍后重试';
                this.isLoading = false;
            }
        },
        
        // 备份数据
        backupData() {
            const data = {
                accounts: this.accounts,
                exportDate: new Date().toISOString()
            };
            
            const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            
            const a = document.createElement('a');
            a.href = url;
            a.download = `password_backup_${new Date().toISOString().split('T')[0]}.json`;
            a.click();
            
            URL.revokeObjectURL(url);
        },
        
        // 生成随机密码
        generateRandomPassword() {
            console.log('generateRandomPassword方法被调用，调用栈:', new Error().stack);
            this.showGeneratePasswordDialog = true;
            this.regeneratePassword();
        },
        
        regeneratePassword() {
            let charset = '';
            if (this.passwordGenerator.includeUppercase) charset += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            if (this.passwordGenerator.includeLowercase) charset += 'abcdefghijklmnopqrstuvwxyz';
            if (this.passwordGenerator.includeNumbers) charset += '0123456789';
            if (this.passwordGenerator.includeSymbols) charset += '!@#$%^&*()_+-=[]{}|;:,.<>?';
            
            if (!charset) {
                charset = 'abcdefghijklmnopqrstuvwxyz0123456789';
            }
            
            let password = '';
            for (let i = 0; i < this.passwordGenerator.length; i++) {
                password += charset.charAt(Math.floor(Math.random() * charset.length));
            }
            
            this.generatedPassword = password;
        },
        
        // 复制生成的密码
        copyGeneratedPassword() {
            navigator.clipboard.writeText(this.generatedPassword).then(() => {
                const tempBtn = document.createElement('button');
                tempBtn.style.position = 'fixed';
                tempBtn.style.opacity = '0';
                tempBtn.textContent = '复制成功';
                document.body.appendChild(tempBtn);
                tempBtn.click();
                document.body.removeChild(tempBtn);
            });
        },
        
        // 应用生成的密码
        applyGeneratedPassword() {
            this.accountForm.password = this.generatedPassword;
            this.showGeneratePasswordDialog = false;
        },
        
        // 验证URL
        validateUrl() {
            if (!this.accountForm.url) {
                this.urlError = '';
                return;
            }
            
            // 验证URL格式：必须以http://或https://开头，并且包含域名点号
            const urlPattern = /^https?:\/\/.+\..+/i;
            if (!urlPattern.test(this.accountForm.url)) {
                this.urlError = 'URL必须以http://或https://开头，并且包含域名';
            } else {
                this.urlError = '';
            }
        },
        
        // 密码强度评估
        evaluatePasswordStrength(password) {
            let strength = 0;
            
            // 长度检查
            if (password.length >= 8) strength += 1;
            if (password.length >= 12) strength += 1;
            if (password.length >= 16) strength += 1;
            
            // 复杂度检查
            if (/[A-Z]/.test(password)) strength += 1;
            if (/[a-z]/.test(password)) strength += 1;
            if (/[0-9]/.test(password)) strength += 1;
            if (/[^A-Za-z0-9]/.test(password)) strength += 1;
            
            return strength;
        },
        
        // 格式化日期
        formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        },
        
        // 获取账号图标
        getAccountIcon(name) {
            return name.charAt(0).toUpperCase();
        }
    }
});